package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 14:26
 */
public class SingleSourcePath1 {
    
    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private int s;
    
    public SingleSourcePath1(Graph G, int s) {
        this.G = G;
        this.s = s;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        G.validateVertex(s);
        Arrays.fill(this.pre, -1);
        dfs(s, s);
    }

    private void dfs(int v, int p) {
        this.visited[v] = true;
        this.pre[v] = p;
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                dfs(w, v);
            }
        }
    }

    public boolean isConnectedTo(int t) {
        G.validateVertex(t);
        return visited[t];
    }

    public Iterable<Integer> path(int t) {
        ArrayList<Integer> path = new ArrayList<>();
        if (!isConnectedTo(t)) {
            return path;
        }
        int cur = t;
        while (cur != s) {
            path.add(cur);
            cur = pre[cur];
        }
        path.add(s);
        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args) {
        String filePath = SingleSourcePath1.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        SingleSourcePath1 singleSourcePath = new SingleSourcePath1(graph, 0);
        System.out.println(singleSourcePath.isConnectedTo(6));
        System.out.println(singleSourcePath.isConnectedTo(5));
        System.out.println(singleSourcePath.path(6));
        System.out.println(singleSourcePath.path(5));
    }
}
